package com.miage.kangourou.client.calendar;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;
import com.miage.kangourou.client.Const;
import com.miage.kangourou.client.GetListesService;
import com.miage.kangourou.client.GetListesServiceAsync;
import com.miage.kangourou.client.beans.Enseignant;
import com.miage.kangourou.client.beans.Evenement;
import com.miage.kangourou.client.beans.Groupe;
import com.miage.kangourou.client.beans.Matiere;
import com.miage.kangourou.client.beans.Promo;
import com.miage.kangourou.client.beans.Salle;
import com.miage.kangourou.client.beans.TypeEvenement;
import com.miage.kangourou.client.beans.Ue;

public class PopupAddEvent {

	private final DialogBox dialogBox = new DialogBox();
	private final boolean databaseConnections[] = new boolean[7];

	private ListBox typeListBox;
	private ListBox ueListBox;
	private ListBox matiereListBox;
	private ListBox promoListBox;
	private ListBox groupeListBox;
	private ListBox professeurListBox;
	private ListBox salleListBox;

	private AsyncCallback<List<Matiere>> changeUe;
	private AsyncCallback<List<Groupe>> changePromo;
	private AsyncCallback<List<Matiere>> Cmatiere;
	private AsyncCallback<List<Ue>> listeUes;
	private AsyncCallback<List<Salle>> listeSalle;
	private AsyncCallback<List<Groupe>> Cgroupe;
	private AsyncCallback<List<Promo>> listePromos;
	private AsyncCallback<List<Enseignant>> listeProfs;
	private AsyncCallback<List<TypeEvenement>> listeTypes;

	// creation service
	private final GetListesServiceAsync getListesService = GWT
			.create(GetListesService.class);

	private void buildAsyncCallBacks() {

		listeTypes = new AsyncCallback<List<TypeEvenement>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}

			public void onSuccess(List<TypeEvenement> result) {

				for (TypeEvenement type : result) {
					typeListBox.addItem(type.getTypeEvenement(), String
							.valueOf(type.getId_type()));
				}

				checkBoxState(0);
			}
		};

		listeProfs = new AsyncCallback<List<Enseignant>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}

			public void onSuccess(List<Enseignant> result) {
				for (Enseignant enseignant : result) {
					professeurListBox.addItem(enseignant.getNom(), String
							.valueOf(enseignant.getId_enseignant()));
				}

				checkBoxState(1);
			}
		};

		listePromos = new AsyncCallback<List<Promo>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}

			public void onSuccess(List<Promo> result) {
				for (Promo promo : result) {
					promoListBox.addItem(promo.getIntitule(), String
							.valueOf(promo.getId_promo()));
				}

				checkBoxState(2);
			}
		};

		Cgroupe = new AsyncCallback<List<Groupe>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());

			}

			public void onSuccess(List<Groupe> result) {
				for (Groupe groupe : result) {
					groupeListBox.addItem(groupe.getIntitule(), String
							.valueOf(groupe.getId_groupe()));
				}

				checkBoxState(3);
			}
		};

		listeSalle = new AsyncCallback<List<Salle>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());

			}

			public void onSuccess(List<Salle> result) {
				for (Salle salle : result) {
					salleListBox.addItem(salle.getIntitule(), String
							.valueOf(salle.getId_salle()));
				}

				checkBoxState(4);
			}
		};

		listeUes = new AsyncCallback<List<Ue>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());

			}

			public void onSuccess(List<Ue> result) {
				for (Ue ue : result) {
					ueListBox.addItem(ue.getIntitule(), String.valueOf(ue
							.getId_ue()));
				}

				checkBoxState(5);
			}
		};

		Cmatiere = new AsyncCallback<List<Matiere>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}

			public void onSuccess(List<Matiere> result) {
				for (Matiere matiere : result) {
					matiereListBox.addItem(matiere.getIntitule(), String
							.valueOf(matiere.getId_matiere()));
				}

				checkBoxState(6);
			}
		};

		changePromo = new AsyncCallback<List<Groupe>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());

			}

			public void onSuccess(List<Groupe> result) {
				groupeListBox.clear();
				for (Groupe groupe : result) {
					groupeListBox.addItem(groupe.getIntitule(), String
							.valueOf(groupe.getId_groupe()));
				}

				checkBoxState(3);
			}
		};

		changeUe = new AsyncCallback<List<Matiere>>() {

			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}

			public void onSuccess(List<Matiere> result) {
				matiereListBox.clear();
				for (Matiere matiere : result) {
					matiereListBox.addItem(matiere.getIntitule(), String
							.valueOf(matiere.getId_matiere()));
				}

				checkBoxState(6);
			}
		};
	}

	private final void checkBoxState(int dataType) {
		if ((dataType >= 0) && (dataType < databaseConnections.length)) {
			databaseConnections[dataType] = true;

			boolean enableBox = true;

			for (int i = 0; i < databaseConnections.length; ++i) {
				if (databaseConnections[i] == false) {
					enableBox = false;
					break;
				}
			}

			if (enableBox) {
				dialogBox.center();
				dialogBox.show();
			}
		}
	}

	/**
	 * @wbp.parser.entryPoint
	 */
	@SuppressWarnings("deprecation")
	public DialogBox show() {

		// initiate the async connections to false
		// will show the form only after all the 7 fields have been filled
		for (int i = 0; i < databaseConnections.length; ++i) {
			databaseConnections[i] = false;
		}

		typeListBox = new ListBox();
		ueListBox = new ListBox();
		matiereListBox = new ListBox();
		promoListBox = new ListBox();
		groupeListBox = new ListBox();
		professeurListBox = new ListBox();
		salleListBox = new ListBox();

		promoListBox.setDirectionEstimator(false);

		groupeListBox.setVisibleItemCount(1);
		groupeListBox.setMultipleSelect(true);
		groupeListBox.setHeight("64px");

		/**
		 * Retrieve data from the database
		 */
		buildAsyncCallBacks();

		getListesService.getTypeList(listeTypes);
		getListesService.getEnseignantList(listeProfs);
		getListesService.getPromoList(listePromos);
		getListesService.getGroupeList(Cgroupe);
		getListesService.getSalleList(listeSalle);
		getListesService.getUEList(listeUes);

		promoListBox.addChangeHandler(new ChangeHandler() {

			public void onChange(ChangeEvent event) {

				getListesService.getGroupeListFromUe(Integer
						.parseInt(promoListBox.getValue(promoListBox
								.getSelectedIndex())), changePromo);

			}
		});

		ueListBox.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				getListesService.getMatiereListFromUe(Integer
						.parseInt(ueListBox.getValue(ueListBox
								.getSelectedIndex())), changeUe);
			}
		});

		getListesService.getMatiereList(Cmatiere);

		dialogBox.setText("NOUVEL EVENEMENT");

		// Recursion - days
		final CheckBox lundi = new CheckBox("Lundi");
		final CheckBox mardi = new CheckBox("Mardi");
		final CheckBox mercredi = new CheckBox("Mercredi");
		final CheckBox jeudi = new CheckBox("Jeudi");
		final CheckBox vendredi = new CheckBox("Vendredi");
		final CheckBox samedi = new CheckBox("Samedi");

		final Label responseMessage = new Label();
		responseMessage.setWidth("100%");
		responseMessage
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		final AsyncCallback<Integer> eventCallback = new AsyncCallback<Integer>() {

			public void onFailure(Throwable caught) {
				responseMessage.setText("L'insertion de l'évènement a échoué.");
				responseMessage.addStyleName("event-add-failure");
			}

			public void onSuccess(Integer result) {
				responseMessage.addStyleName("event-add-success");

				if (result == 1) {
					responseMessage.setText("L'évènement a été ajouté !");
				} else {
					responseMessage.setText(result
							+ " évènements ont été ajoutés !");
				}

			}
		};

		final DisclosurePanel simpleCreationPanel = new DisclosurePanel(
				"Evènement simple");
		final DisclosurePanel recurrentCreationPanel = new DisclosurePanel(
				"Evènement avec répétition");
		final DisclosurePanel timeSlotCreationPanel = new DisclosurePanel(
				"Recherche de créneaux libres");

		simpleCreationPanel.setWidth("400px");
		recurrentCreationPanel.setWidth("400px");
		timeSlotCreationPanel.setWidth("400px");

		HorizontalPanel header = new HorizontalPanel();
		HorizontalPanel body = new HorizontalPanel();
		VerticalPanel body2 = new VerticalPanel();

		VerticalPanel footer = new VerticalPanel();
		HorizontalPanel footer2 = new HorizontalPanel();

		VerticalPanel container = new VerticalPanel();

		final Button validateEventCreation = new Button("Créer");

		/**
		 * left part of the body
		 */
		Grid grid = new Grid(7, 2);

		grid.setWidget(0, 1, typeListBox);
		grid.setWidget(1, 1, ueListBox);
		grid.setWidget(2, 1, matiereListBox);
		grid.setWidget(3, 1, promoListBox);
		grid.setWidget(4, 1, groupeListBox);
		grid.setWidget(5, 1, professeurListBox);
		grid.setWidget(6, 1, salleListBox);

		grid.setWidget(0, 0, new Label("Type"));
		grid.setWidget(1, 0, new Label("Ue"));
		grid.setWidget(2, 0, new Label("Matiere"));
		grid.setWidget(3, 0, new Label("Promo"));
		grid.setWidget(4, 0, new Label("Groupe"));
		grid.setWidget(5, 0, new Label("Professeur"));
		grid.setWidget(6, 0, new Label("Salle"));

		/**
		 * Right part of the body
		 */

		// Add a basic event

		final ListBox heureDebutSimple = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureDebutSimple.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minDebutSimple = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minDebutSimple.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox heureFinSimple = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureFinSimple.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minFinSimple = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minFinSimple.addItem(String.valueOf(i), String.valueOf(i));
		}

		final DateBox dateDebutSimple = new DateBox();
		dateDebutSimple.setValue(new Date());
		dateDebutSimple.setFormat(new DateBox.DefaultFormat(DateTimeFormat
				.getShortDateFormat()));

		VerticalPanel simpleCreationPanel2 = new VerticalPanel();
		Grid simpleCreationGrid = new Grid(3, 2);
		simpleCreationGrid.setWidget(0, 0, new Label("Date"));
		simpleCreationGrid.setWidget(0, 1, dateDebutSimple);

		simpleCreationGrid.setWidget(1, 0, new Label("De"));

		HorizontalPanel dateStartSimplePanel = new HorizontalPanel();
		dateStartSimplePanel.add(heureDebutSimple);
		dateStartSimplePanel.add(new Label(":"));
		dateStartSimplePanel.add(minDebutSimple);
		simpleCreationGrid.setWidget(1, 1, dateStartSimplePanel);

		simpleCreationGrid.setWidget(2, 0, new Label("A"));
		HorizontalPanel dateEndSimplePanel = new HorizontalPanel();
		dateEndSimplePanel.add(heureFinSimple);
		dateEndSimplePanel.add(new Label(":"));
		dateEndSimplePanel.add(minFinSimple);
		simpleCreationGrid.setWidget(2, 1, dateEndSimplePanel);

		final TextArea commentTextSimple = new TextArea();
		commentTextSimple.setVisibleLines(2);
		commentTextSimple.setWidth("100%");

		simpleCreationPanel2.add(simpleCreationGrid);
		simpleCreationPanel2.add(commentTextSimple);

		simpleCreationPanel2.setCellHorizontalAlignment(commentTextSimple,
				HasHorizontalAlignment.ALIGN_CENTER);

		simpleCreationPanel.add(simpleCreationPanel2);

		simpleCreationPanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {

			public void onOpen(OpenEvent<DisclosurePanel> event) {
				timeSlotCreationPanel.setOpen(false);
				recurrentCreationPanel.setOpen(false);
				validateEventCreation.setEnabled(true);
				dialogBox.center();
			}
		});

		// Add a recurrent event
		final DateBox dateDebutRecurrent = new DateBox();
		dateDebutRecurrent.setValue(new Date());
		dateDebutRecurrent.setFormat(new DateBox.DefaultFormat(DateTimeFormat
				.getShortDateFormat()));

		final ListBox heureDebutRecurrent = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureDebutRecurrent.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minDebutRecurrent = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minDebutRecurrent.addItem(String.valueOf(i), String.valueOf(i));
		}

		final DateBox dateFinRecurrent = new DateBox();
		dateFinRecurrent.setValue(new Date());
		dateFinRecurrent.setFormat(new DateBox.DefaultFormat(DateTimeFormat
				.getShortDateFormat()));

		final ListBox heureFinRecurrent = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureFinRecurrent.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minFinRecurrent = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minFinRecurrent.addItem(String.valueOf(i), String.valueOf(i));
		}

		VerticalPanel recurrentCreationPanel2 = new VerticalPanel();

		Grid recurrentCreationGrid = new Grid(2, 5);
		recurrentCreationGrid.setWidget(0, 0,
				new Label("Date début répétition"));
		recurrentCreationGrid.setWidget(0, 1, dateDebutRecurrent);
		recurrentCreationGrid.setWidget(0, 2, heureDebutRecurrent);
		recurrentCreationGrid.setWidget(0, 3, new Label(":"));
		recurrentCreationGrid.setWidget(0, 4, minDebutRecurrent);

		recurrentCreationGrid.setWidget(1, 0, new Label("Date fin répétition"));
		recurrentCreationGrid.setWidget(1, 1, dateFinRecurrent);
		recurrentCreationGrid.setWidget(1, 2, heureFinRecurrent);
		recurrentCreationGrid.setWidget(1, 3, new Label(":"));
		recurrentCreationGrid.setWidget(1, 4, minFinRecurrent);

		HorizontalPanel recursionDays = new HorizontalPanel();

		recursionDays.add(lundi);
		recursionDays.add(mardi);
		recursionDays.add(mercredi);
		recursionDays.add(jeudi);
		recursionDays.add(vendredi);
		recursionDays.add(samedi);

		recursionDays.setSpacing(2);

		final TextArea commentTextRecurrent = new TextArea();
		commentTextRecurrent.setVisibleLines(2);
		commentTextRecurrent.setWidth("100%");

		recurrentCreationPanel2.add(recurrentCreationGrid);
		recurrentCreationPanel2.add(recursionDays);
		recurrentCreationPanel2.add(commentTextRecurrent);

		recurrentCreationPanel2.setWidth("100%");
		recurrentCreationPanel2.setCellHorizontalAlignment(recursionDays,
				HasHorizontalAlignment.ALIGN_CENTER);

		recurrentCreationPanel.add(recurrentCreationPanel2);

		recurrentCreationPanel
				.addOpenHandler(new OpenHandler<DisclosurePanel>() {

					public void onOpen(OpenEvent<DisclosurePanel> event) {
						simpleCreationPanel.setOpen(false);
						timeSlotCreationPanel.setOpen(false);
						validateEventCreation.setEnabled(true);
						dialogBox.center();
					}
				});

		// Find free time slots
		final DateBox dateDebutTimeSlot = new DateBox();
		dateDebutTimeSlot.setValue(new Date());
		dateDebutTimeSlot.setFormat(new DateBox.DefaultFormat(DateTimeFormat
				.getShortDateFormat()));

		final ListBox heureDebutTimeSlot = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureDebutTimeSlot.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minDebutTimeSlot = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minDebutTimeSlot.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox heureFinTimeSlot = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_H; i <= Const.CALENDAR_DISPLAY_STOP_H; ++i) {
			heureFinTimeSlot.addItem(String.valueOf(i), String.valueOf(i));
		}

		final ListBox minFinTimeSlot = new ListBox();
		for (int i = Const.CALENDAR_DISPLAY_START_MIN; i < 60; i += Const.CALENDAR_DISPLAY_INTERVAL_MIN) {
			minFinTimeSlot.addItem(String.valueOf(i), String.valueOf(i));
		}

		VerticalPanel timeSlotVerticalPanel = new VerticalPanel();
		Grid timeSlotCreationGrid = new Grid(2, 2);
		timeSlotCreationGrid.setWidget(0, 0, new Label("A partir de"));
		timeSlotCreationGrid.setWidget(0, 1, dateDebutTimeSlot);
		timeSlotCreationGrid.setWidget(1, 0, new Label("Entre"));

		HorizontalPanel timeSlotPanel = new HorizontalPanel();

		timeSlotPanel.add(heureDebutTimeSlot);
		timeSlotPanel.add(minDebutTimeSlot);
		timeSlotPanel.add(new Label(" et "));
		timeSlotPanel.add(heureFinTimeSlot);
		timeSlotPanel.add(minFinTimeSlot);
		timeSlotPanel.setSpacing(2);

		timeSlotCreationGrid.setWidget(1, 1, timeSlotPanel);

		final VerticalPanel timeSlotResponses = new VerticalPanel();

		Button findTimeSlot = new Button("Chercher", new ClickHandler() {
			public void onClick(ClickEvent event) {

				final AsyncCallback<List<Date>> creneauAsync = new AsyncCallback<List<Date>>() {

					public void onFailure(Throwable caught) {
						Window.alert("Erreur lors de l'appel serveur "
								+ caught.getMessage());

					}

					public void onSuccess(List<Date> creneau) {

						timeSlotResponses.clear();

						Label creneauxLabel = new Label(
								"Creneaux disponibles : ");
						final ListBox creneaux = new ListBox();

						creneaux.addChangeHandler(new ChangeHandler() {

							public void onChange(ChangeEvent event) {
								String[] timestamps;
								timestamps = creneaux.getValue(
										creneaux.getSelectedIndex()).split("-");

								if (timestamps.length == 2) {

									Date debut = new Date();
									debut
											.setTime(Long
													.parseLong(timestamps[0]));
									Date fin = new Date();
									fin.setTime(Long.parseLong(timestamps[1]));

									dateDebutSimple.setValue(debut);

									int heureDebut = debut.getHours();
									for (int i = 0; i < heureDebutSimple
											.getItemCount(); ++i) {
										if (Integer.parseInt(heureDebutSimple
												.getValue(i)) == heureDebut) {
											heureDebutSimple
													.setSelectedIndex(i);
											break;
										}
									}

									int minuteDebut = debut.getMinutes();
									for (int i = 0; i < minDebutSimple
											.getItemCount(); ++i) {
										if (Integer.parseInt(minDebutSimple
												.getValue(i)) == minuteDebut) {
											minDebutSimple.setSelectedIndex(i);
											break;
										}
									}

									int heureFin = fin.getHours();
									for (int i = 0; i < heureFinSimple
											.getItemCount(); ++i) {
										if (Integer.parseInt(heureFinSimple
												.getValue(i)) == heureFin) {
											heureFinSimple.setSelectedIndex(i);
											break;
										}
									}

									int minFin = fin.getMinutes();
									for (int i = 0; i < minFinSimple
											.getItemCount(); ++i) {
										if (Integer.parseInt(minFinSimple
												.getValue(i)) == minFin) {
											minFinSimple.setSelectedIndex(i);
											break;
										}
									}
								}
							}
						});

						timeSlotResponses.add(creneauxLabel);
						timeSlotResponses.add(creneaux);

						for (int i = 0; i < creneau.size(); i += 2) {
							creneaux
									.addItem(
											(creneau.get(i).getDate() < 10 ? "0"
													+ creneau.get(i).getDate()
													: creneau.get(i).getDate())
													+ "/"
													+ ((creneau.get(i)
															.getMonth() + 1) < 10 ? "0"
															+ (creneau.get(i)
																	.getMonth() + 1)
															: (creneau.get(i)
																	.getMonth() + 1))
													+ " - entre "
													+ (creneau.get(i)
															.getHours() < 10 ? "0"
															+ creneau.get(i)
																	.getHours()
															: creneau.get(i)
																	.getHours())
													+ ":"
													+ (creneau.get(i)
															.getMinutes() < 10 ? "0"
															+ creneau
																	.get(i)
																	.getMinutes()
															: creneau
																	.get(i)
																	.getMinutes())
													+ " et "
													+ (creneau.get(i + 1)
															.getHours() < 10 ? "0"
															+ creneau
																	.get(i + 1)
																	.getHours()
															: creneau
																	.get(i + 1)
																	.getHours())
													+ ":"
													+ (creneau.get(i + 1)
															.getMinutes() < 10 ? "0"
															+ creneau
																	.get(i + 1)
																	.getMinutes()
															: creneau
																	.get(i + 1)
																	.getMinutes()),
											creneau.get(i).getTime()
													+ "-"
													+ creneau.get(i + 1)
															.getTime());

							System.out.println(creneau.get(i).getTime() + "-"
									+ creneau.get(i + 1).getTime());
						}
					}
				};

				ArrayList<Integer> groupes = new ArrayList<Integer>();

				for (int i = 0; i < groupeListBox.getItemCount(); i++) {
					if (groupeListBox.isItemSelected(i)) {
						groupes
								.add(Integer
										.parseInt(groupeListBox.getValue(i)));
					}
				}

				getListesService
						.findCreneauxLibres(groupes, dateDebutTimeSlot
								.getValue(), Integer
								.parseInt(heureDebutTimeSlot
										.getValue(heureDebutTimeSlot
												.getSelectedIndex())), Integer
								.parseInt(minDebutTimeSlot
										.getValue(minDebutTimeSlot
												.getSelectedIndex())), Integer
								.parseInt(heureFinTimeSlot
										.getValue(heureFinTimeSlot
												.getSelectedIndex())), Integer
								.parseInt(minFinTimeSlot
										.getValue(minFinTimeSlot
												.getSelectedIndex())),
								creneauAsync);
			}
		});

		timeSlotVerticalPanel.add(timeSlotCreationGrid);
		timeSlotVerticalPanel.add(findTimeSlot);
		timeSlotVerticalPanel.add(timeSlotResponses);

		timeSlotCreationPanel.add(timeSlotVerticalPanel);

		timeSlotCreationPanel
				.addOpenHandler(new OpenHandler<DisclosurePanel>() {

					public void onOpen(OpenEvent<DisclosurePanel> event) {
						simpleCreationPanel.setOpen(false);
						recurrentCreationPanel.setOpen(false);
						validateEventCreation.setEnabled(false);
						dialogBox.center();
					}
				});

		/**
		 * Footer
		 */

		final Button cancelEventCreation = new Button("Annuler",
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						dialogBox.hide();
					}
				});

		validateEventCreation.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				if (simpleCreationPanel.isOpen()) {
					Date startDate = dateDebutSimple.getValue();
					startDate.setHours(Integer.parseInt(heureDebutSimple
							.getValue(heureDebutSimple.getSelectedIndex())));
					startDate.setMinutes(Integer.parseInt(minDebutSimple
							.getValue(minDebutSimple.getSelectedIndex())));

					Date endDate = (Date) dateDebutSimple.getValue().clone();
					endDate.setHours(Integer.parseInt(heureFinSimple
							.getValue(heureFinSimple.getSelectedIndex())));
					endDate.setMinutes(Integer.parseInt(minFinSimple
							.getValue(minFinSimple.getSelectedIndex())));

					if (endDate.before(startDate)) {
						responseMessage
								.setText("Veuillez vérifier les heures de début et de fin de l'évènement");
						responseMessage.addStyleName("event-add-failure");
					} else {

						for (int i = 0; i <= groupeListBox.getItemCount(); i++) {
							if (groupeListBox.isItemSelected(i)) {
								Evenement evt = new Evenement(0, Integer
										.parseInt(salleListBox
												.getValue(salleListBox
														.getSelectedIndex())),
										Integer.parseInt(typeListBox
												.getValue(typeListBox
														.getSelectedIndex())),
										Integer.parseInt(professeurListBox
												.getValue(professeurListBox
														.getSelectedIndex())),
										Integer.parseInt(matiereListBox
												.getValue(matiereListBox
														.getSelectedIndex())),
										Integer.parseInt(groupeListBox
												.getValue(i)),
										commentTextSimple.getValue(),
										startDate, endDate, 0);
								getListesService
										.createEvent(evt, eventCallback);
							}
						}
					}
				} else if (recurrentCreationPanel.isOpen()) {

					if ((lundi.getValue() || mardi.getValue()
							|| mercredi.getValue() || jeudi.getValue()
							|| vendredi.getValue() || samedi.getValue()) == false) {
						responseMessage
								.setText("Il faut qu'au moins un jour soit coché !");
						responseMessage.addStyleName("event-add-failure");
					} else {
						Date startDate = dateDebutRecurrent.getValue();
						startDate.setHours(Integer.parseInt(heureDebutRecurrent
								.getValue(heureDebutRecurrent
										.getSelectedIndex())));
						startDate.setMinutes(Integer
								.parseInt(minDebutRecurrent
										.getValue(minDebutRecurrent
												.getSelectedIndex())));

						Date endDate = (Date) dateDebutRecurrent.getValue()
								.clone();
						endDate.setHours(Integer
								.parseInt(heureFinRecurrent
										.getValue(heureFinRecurrent
												.getSelectedIndex())));
						endDate.setMinutes(Integer.parseInt(minFinRecurrent
								.getValue(minFinRecurrent.getSelectedIndex())));

						if (dateDebutRecurrent.getValue().after(
								dateFinRecurrent.getValue())) {
							responseMessage.addStyleName("event-add-failure");
							responseMessage
									.setText("La date de fin doit être après la date de début!");

						} else {
							ArrayList<Integer> joursCoches = new ArrayList<Integer>();

							if (lundi.getValue()) {
								joursCoches.add(1);
							}

							if (mardi.getValue()) {
								joursCoches.add(2);
							}

							if (mercredi.getValue()) {
								joursCoches.add(3);
							}

							if (jeudi.getValue()) {
								joursCoches.add(4);
							}

							if (vendredi.getValue()) {
								joursCoches.add(5);
							}

							if (samedi.getValue()) {
								joursCoches.add(6);
							}

							for (int i = 0; i <= groupeListBox.getItemCount(); i++) {
								if (groupeListBox.isItemSelected(i)) {
									Evenement evtRecurrent = new Evenement(
											0,
											Integer
													.parseInt(salleListBox
															.getValue(salleListBox
																	.getSelectedIndex())),
											Integer
													.parseInt(typeListBox
															.getValue(typeListBox
																	.getSelectedIndex())),
											Integer
													.parseInt(professeurListBox
															.getValue(professeurListBox
																	.getSelectedIndex())),
											Integer
													.parseInt(matiereListBox
															.getValue(matiereListBox
																	.getSelectedIndex())),
											Integer.parseInt(groupeListBox
													.getValue(i)),
											commentTextRecurrent.getValue(),
											startDate, endDate, 0);

									getListesService.createEventRecurrence(
											evtRecurrent, startDate, endDate,
											joursCoches, eventCallback);
								}
							}
						}
					}

				} else if (timeSlotCreationPanel.isOpen()) {

				}

				cancelEventCreation.setText("Fermer");
			}
		});

		footer.setWidth("100%");
		footer.setSpacing(2);

		footer2.setWidth("100%");
		footer2.add(validateEventCreation);
		footer2.setCellWidth(validateEventCreation, "50%");
		footer2.setCellHorizontalAlignment(validateEventCreation,
				HasHorizontalAlignment.ALIGN_RIGHT);
		footer2.setCellHorizontalAlignment(cancelEventCreation,
				HasHorizontalAlignment.ALIGN_LEFT);

		footer2.add(cancelEventCreation);

		footer.add(footer2);
		footer.add(responseMessage);
		footer.setCellHorizontalAlignment(responseMessage,
				HasHorizontalAlignment.ALIGN_CENTER);

		/**
		 * Pop up hierarchy
		 */

		body2.add(simpleCreationPanel);
		body2.add(recurrentCreationPanel);
		body2.add(timeSlotCreationPanel);

		body.add(grid);
		body.add(body2);

		container.setWidth("100%");
		container.add(header);
		container.add(body);
		container.add(footer);

		dialogBox.add(container);

		return dialogBox;
	}
}
